package com.example.demo.controller;

import cn.hutool.core.util.ObjUtil;
import com.example.demo.base.baseController;
import com.example.demo.constant.SecurityConstant;
import com.example.demo.entity.Car;
import com.example.demo.entity.User;
import com.example.demo.entity.UserRole;
import com.example.demo.entity.vo.UserVo;
import com.example.demo.service.UserRoleService;
import com.example.demo.service.UserService;
import com.example.demo.util.JwtUtil;
import com.example.demo.util.StringUtil;
import com.example.demo.vo.Result;
import com.example.demo.vo.ResultCode;
import io.jsonwebtoken.Claims;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.constraints.NotEmpty;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;


/**
 * @author Mr.Tang
 */
@Tag(name = "用户接口")
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController extends baseController<UserService, User> {

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private UserRoleService userRoleService;

    @Resource
    private JwtUtil jwtUtil;

    /**
     * 用户注册
     * @param username 用户名
     * @param password 密码
     * @return 返回
     */
    @Operation(summary = "注册接口")
    @PostMapping("/register")
    public Result register(@Parameter(name = "username", description = "用户名", required = true) @NonNull String username,
                           @Parameter(name = "password", description = "密码", required = true) @NonNull String password) {
        // 准备数据
        User user = new User();
        user.setUsername(username);
        // 密文处理
        String ciphertext = passwordEncoder.encode(password);
        user.setPassword(ciphertext);
        
        // 调用service
        baseService.save(user);
        
        // 角色表新增
        // 获取用户id
        Long userId = baseService.getUserId(username);
        UserRole userRole = new UserRole();
        userRole.setUserId(userId);
        userRole.setRoleId(2L);
        userRoleService.addUserRole(userRole);

        return Result.ok(ResultCode.SUCCESS);
    }


    @Operation(summary = "根据用户id获取当前用户信息")
    @GetMapping("/getUserInfoByUserId")
    public Result<User> getUserInfoByUserId(@Parameter(name = "userId", description = "用户id", required = true) @NonNull Long userId) {
        // 调用service
        User user = baseService.getUserInfoByUserId(userId);
        // 返回
        return Result.ok(user);
    }


    @Operation(summary = "重置密码")
    @PostMapping("/resetPassword")
    public Result resetPassword(@Parameter(name = "username", description = "用户名", required = true) @NonNull String username,
                                @Parameter(name = "password", description = "密码", required = true) @NonNull String password) {
        baseService.resetPassword(username, password);
        return Result.ok(ResultCode.SUCCESS);
    }


    @Operation(summary = "修改密码")
    @PostMapping("/modifyPwd")
    public Result modifyPassword(HttpServletRequest request,
                                 @Parameter(name = "oldPassword", description = "旧密码", required = true) String oldPassword,
                                 @Parameter(name = "newPassword", description = "新密码", required = true) String newPassword) throws Exception {
        // 1. 获取当前用户登录信息
        // 获取jwtToken
        String jwtToken = request.getHeader(SecurityConstant.TOKEN_HEADER);
        if (ObjUtil.isEmpty(jwtToken)) {
            log.warn("状态异常");
            return Result.error(ResultCode.CLIENT_A0300);
        }
        // 解析jwtToken
        Claims claims = jwtUtil.parse(jwtToken);
        String username = claims.getSubject();
        if (StringUtil.isEmpty(username)) {
            log.warn("状态异常");
            return Result.error(ResultCode.CLIENT_A0300);
        }

        // 2. 调用service
        baseService.modifyPassword(username, oldPassword, newPassword);

        // 3. 成功返回
        return Result.ok(ResultCode.SUCCESS);
    }


    @Operation(summary = "修改个人信息")
    @PostMapping("/modifyInfo")
    public Result modifyInfo(HttpServletRequest request,
                             @Parameter(name = "nickname", description = "昵称") String nickname,
                             @Parameter(name = "gender", description = "性别") String gender,
                             @Parameter(name = "phone", description = "手机号码") String phone,
                             @Parameter(name = "email", description = "邮箱") String email,
                             @Parameter(name = "avatarPath", description = "头像地址") String avatarPath) throws Exception {
        // 1. 封装对象
        // 从token拿到username
        String jwtToken = request.getHeader(SecurityConstant.TOKEN_HEADER);
        if (ObjUtil.isEmpty(jwtToken)) {
            log.warn("状态异常");
            return Result.error(ResultCode.CLIENT_A0300);
        }
        // 解析jwtToken
        Claims claims = jwtUtil.parse(jwtToken);
        String username = claims.getSubject();
        if (StringUtil.isEmpty(username)) {
            log.warn("状态异常");
            return Result.error(ResultCode.CLIENT_A0300);
        }
        User updateUser = new User();
        updateUser.setUsername(username);
        updateUser.setNickname(nickname);
        updateUser.setGender(gender);
        updateUser.setPhone(phone);
        updateUser.setEmail(email);
        updateUser.setAvatarPath(avatarPath);

        // 设置更新时间
        LocalDateTime dateTime = LocalDateTime.now();
        updateUser.setUpdateTime(dateTime);

        // 2. 调用 service
        baseService.modifyInfo(updateUser);

        // 3. 返回
        return Result.ok(ResultCode.SUCCESS);
    }


    @Operation(summary = "用户上传头像")
    @PostMapping("/uploadAvatar2")
    public Result uploadAvatar(HttpServletRequest request,
                               @Parameter(name = "avatar", description = "用户头像文件", required = true) MultipartFile avatar) throws Exception {
        // 1. 拿到当前用户
        // 从token拿到username
        String jwtToken = request.getHeader(SecurityConstant.TOKEN_HEADER);
        if (ObjUtil.isEmpty(jwtToken)) {
            log.warn("状态异常");
            return Result.error(ResultCode.CLIENT_A0300);
        }
        // 解析jwtToken
        Claims claims = jwtUtil.parse(jwtToken);
        String username = claims.getSubject();
        if (StringUtil.isEmpty(username)) {
            log.warn("状态异常");
            return Result.error(ResultCode.CLIENT_A0300);
        }

        // 2. 处理文件
        // 获取文件名
        String fileName = avatar.getOriginalFilename();
        // 指定文件存储路径
        String filePath = "D:\\Huike\\RBAC\\GitRepository\\demo\\src\\main\\resources\\static\\image\\" + fileName;

        // 3. 封装新对象
        User user = new User();
        user.setUsername(username);
        user.setAvatarName(fileName);
        user.setAvatarPath(filePath);
        user.setUpdateTime(LocalDateTime.now());

        // 4. 调用service
        baseService.uploadAvatar(user);

        // 保存图片
        File dest = new File(filePath);
        avatar.transferTo(dest);

        return Result.ok(filePath);
    }



    @PostMapping("/uploadAvatar")
    public Result<String> upload(HttpServletRequest request,
            @RequestParam("file") MultipartFile file) throws IOException {
        //将图片上传到本地磁盘
        String originalFilename = file.getOriginalFilename();
        System.out.println("执行了upload");
        // 获取当前时间戳
        String timestamp = String.valueOf(System.currentTimeMillis());

        // 获取原始文件名的扩展名
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));

        // 组合新的文件名
        String filename = timestamp + fileExtension;
        file.transferTo(new File("D:\\Huike\\RBAC\\GitRepository\\demo\\src\\main\\resources\\static\\image\\" + filename));
        File uploadedFile = new File("D:\\Huike\\RBAC\\GitRepository\\demo\\src\\main\\resources\\static\\image\\" + filename);

        boolean re= uploadedFile.exists();

        if(re){
            return Result.ok(filename);
        }else {
            return Result.error(ResultCode.CLIENT_A3015);
        }
    }


    @Operation(summary = "获取当前登录用户id")
    @GetMapping("/getUserId")
    public Result<Long> getInfo(@Parameter(name = "username", description = "用户名", required = true) @NonNull String username) {
        // 1. 调用service
        Long userId = baseService.getUserId(username);

        // 2. 成功返回
        return Result.ok(userId);
    }

    @Operation(summary = "获取当前登录用户角色")
    @GetMapping("/getRoleByUsername")
    public ArrayList<String> getRoleByUsername(@Parameter(name = "username", description = "用户名", required = true) @NonNull String username) {

        return baseService.getRoleByUsername(username);
    }

    @Operation(summary = "获取所有的用户角色列表")
    @GetMapping("/getAllUserWithRole")
    public Result<List<UserVo>> getAllUserWithRole() {
        // 调用service
        List<UserVo> list = baseService.getAllUserWithRole();
        // 成功返回
        return Result.ok(list);
    }

    @Operation(summary = "修改用户角色")
    @PostMapping("/modifyUserRole")
    public Result modifyUserRole(@Parameter(name = "userId", description = "用户id") @NonNull Long userId,
                                 @RequestBody @NotEmpty List<Long> roles) {
        // 调用service
        baseService.modifyUserRole(userId, roles);
        // 成功返回
        return Result.ok();
    }


    @Operation(summary = "修改用户状态")
    @PostMapping("/ModifyUserStatus")
    public Result ModifyUserStatus(@Parameter(name = "userId", description = "用户id") @NonNull Long userId) {
        // 调用service
        baseService.ModifyUserStatus(userId);
        // 成功返回
        return Result.ok();
    }



}
